<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片标注测距工具</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        body {
            background-color: #f8f9fa;
            min-height: 100vh;
            padding: 20px;
            color: #343a40;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        header {
            text-align: center;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            position: relative;
        }

        .back-to-home {
            position: absolute;
            left: 30px;
            top: 50%;
            transform: translateY(-50%);
            padding: 8px 16px;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
            color: #495057;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s ease;
        }

        .back-to-home:hover {
            background: #e9ecef;
            color: #212529;
        }
        
        h1 {
            font-size: 2rem;
            color: #495057;
            margin-bottom: 8px;
            font-weight: 600;
        }
        
        .description {
            font-size: 1rem;
            color: #6c757d;
            max-width: 800px;
            margin: 0 auto;
            line-height: 1.5;
        }
        
        .main-content {
            display: flex;
            gap: 20px;
            min-height: 600px;
        }
        
        .tool-panel {
            flex: 0 0 240px;
            background: white;
            border-radius: 8px;
            padding: 18px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .tool-section {
            margin-bottom: 12px;
        }
        
        .tool-section h3 {
            margin-bottom: 8px;
            padding-bottom: 6px;
            border-bottom: 1px solid #e9ecef;
            color: #495057;
            font-size: 0.95rem;
            font-weight: 600;
        }
        
        .btn {
            padding: 9px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s ease;
            width: 100%;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 0.9rem;
        }
        
        .btn-primary {
            background: #4080ff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #3366cc;
        }
        
        .btn-success {
            background: #36b37e;
            color: white;
        }
        
        .btn-success:hover {
            background: #2d9768;
        }
        
        .btn-danger {
            background: #ff5630;
            color: white;
        }
        
        .btn-danger:hover {
            background: #cc4526;
        }
        
        .btn-outline {
            background: transparent;
            border: 1px solid #e9ecef;
            color: #495057;
        }
        
        .btn-outline:hover {
            background: #f1f3f5;
        }
        
        .canvas-container {
            flex: 1;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            position: relative;
        }
        
        #ruler {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 28px;
            background: #f8f9fa;
            z-index: 10;
            color: #6c757d;
            display: flex;
            align-items: center;
            padding: 0 12px;
            font-size: 0.85rem;
            border-bottom: 1px solid #e9ecef;
        }
        
        #workspace {
            position: absolute;
            top: 28px;
            left: 0;
            right: 0;
            bottom: 0;
            overflow: hidden;
            background: #fafbfc;
            cursor: grab;
        }
        
        #imageCanvas {
            position: absolute;
            transform-origin: 0 0;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        }
        
        #overlayCanvas {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 20;
        }
        
        .measure-info {
            position: absolute;
            top: 40px;
            right: 20px;
            background: white;
            color: #495057;
            padding: 12px 15px;
            border-radius: 6px;
            min-width: 180px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
            font-size: 0.9rem;
        }
        
        .info-item {
            margin-bottom: 7px;
            display: flex;
            justify-content: space-between;
            line-height: 1.4;
        }
        
        .info-label {
            color: #6c757d;
        }
        
        .info-value {
            font-weight: 500;
            color: #4080ff;
        }
        
        .instructions {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        
        .instructions h2 {
            color: #495057;
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e9ecef;
            font-size: 1.2rem;
            font-weight: 600;
        }
        
        .instructions ul {
            padding-left: 20px;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 8px;
            font-size: 0.95rem;
            color: #495057;
        }
        
        .instructions li {
            margin-bottom: 8px;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 4px;
            line-height: 1.5;
        }
        
        .instructions li strong {
            color: #4080ff;
            font-weight: 500;
        }
        
        .grid-background {
            display: none;
        }
        
        .zoom-controls {
            position: absolute;
            bottom: 20px;
            right: 20px;
            display: flex;
            gap: 8px;
            background: white;
            padding: 8px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }
        
        .zoom-btn {
            width: 36px;
            height: 36px;
            border-radius: 4px;
            background: #f1f3f5;
            color: #495057;
            border: none;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.2s;
        }
        
        .zoom-btn:hover {
            background: #e9ecef;
        }
        
        .zoom-display {
            color: #495057;
            display: flex;
            align-items: center;
            padding: 0 12px;
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        .mode-indicator {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background: white;
            color: #495057;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 0.85rem;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            display: none;
        }

        .color-picker-container {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
            padding: 8px 0;
            font-size: 0.9rem;
        }

        #lineColor {
            width: 36px;
            height: 36px;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            cursor: pointer;
            padding: 0;
            background: transparent;
        }
        
        @media (max-width: 900px) {
            .main-content {
                flex-direction: column;
            }
            
            .tool-panel {
                flex: 0 0 auto;
                flex-direction: row;
                flex-wrap: wrap;
                justify-content: space-between;
            }
            
            .tool-section {
                flex: 0 0 48%;
                margin-bottom: 10px;
            }
            
            .instructions ul {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <button class="back-to-home" onclick="window.location.href='index.html'">
                <i class="fas fa-home"></i> 返回首页
            </button>
            <h1>图片标注测距工具</h1>
            <p class="description">精确测量图片上任意两点间距离，支持水平与垂直测量，自定义标注样式</p>
        </header>
        
        <div class="main-content">
            <div class="tool-panel">
                <div class="tool-section">
                    <h3>图片操作</h3>
                    <button class="btn btn-primary" id="uploadBtn">
                        <span>📁</span> 上传图片
                    </button>
                    <input type="file" id="imageUpload" accept="image/*" style="display: none;">
                </div>
                
                <div class="tool-section">
                    <h3>测量工具</h3>
                    <button class="btn btn-success" id="measureBtn">
                        <span>📏</span> 开始测量
                    </button>
                    <button class="btn btn-danger" id="clearBtn">
                        <span>🗑️</span> 清除标注
                    </button>
                    <div class="color-picker-container">
                        <label for="lineColor" class="info-label">标注颜色:</label>
                        <input type="color" id="lineColor" value="#e74c3c">
                    </div>
                </div>
                
                <div class="tool-section">
                    <h3>视图控制</h3>
                    <button class="btn btn-outline" id="zoomInBtn">
                        <span>➕</span> 放大
                    </button>
                    <button class="btn btn-outline" id="zoomOutBtn">
                        <span>➖</span> 缩小
                    </button>
                    <button class="btn btn-outline" id="resetViewBtn">
                        <span>↺</span> 重置视图
                    </button>
                </div>
                
                <div class="tool-section">
                    <h3>测量信息</h3>
                    <div class="info-item">
                        <span class="info-label">状态:</span>
                        <span id="statusValue" class="info-value">就绪</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">距离:</span>
                        <span id="distanceValue" class="info-value">0 像素</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">缩放:</span>
                        <span id="zoomValue" class="info-value">100%</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">模式:</span>
                        <span id="modeValue" class="info-value">水平/垂直</span>
                    </div>
                </div>
            </div>
            
            <div class="canvas-container">
                <div id="ruler">操作提示：滚轮缩放 | 拖动调整位置</div>
                <div id="workspace">
                    <div class="grid-background"></div>
                    <canvas id="imageCanvas"></canvas>
                    <canvas id="overlayCanvas"></canvas>
                </div>
                
                <div class="zoom-controls">
                    <button class="zoom-btn" id="zoomOutBtnSmall">-</button>
                    <div class="zoom-display" id="zoomDisplay">100%</div>
                    <button class="zoom-btn" id="zoomInBtnSmall">+</button>
                </div>
                
                <div class="mode-indicator" id="modeIndicator">
                    当前模式: <span id="currentMode">水平/垂直测量</span>
                </div>
            </div>
        </div>
        
        <div class="instructions">
            <h2>使用说明</h2>
            <ul>
                <li><strong>上传图片</strong> - 点击"上传图片"按钮选择需要测量的图片，上传新图片会自动清除之前的标注</li>
                <li><strong>开始测量</strong> - 点击"开始测量"按钮，进入测量模式</li>
                <li><strong>选择起点</strong> - 在图片上点击确定测量起点位置</li>
                <li><strong>确定终点</strong> - 移动鼠标到终点（自动限制水平/垂直方向）</li>
                <li><strong>完成测量</strong> - 点击确认终点，系统自动计算并显示距离</li>
                <li><strong>视图调整</strong> - 使用滚轮或按钮缩放图片，直接拖动调整位置</li>
                <li><strong>清除标记</strong> - 点击"清除标注"按钮移除所有测量痕迹</li>
                <li><strong>样式自定义</strong> - 通过颜色选择器更改标注线的显示颜色</li>
            </ul>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            const uploadBtn = document.getElementById('uploadBtn');
            const imageUpload = document.getElementById('imageUpload');
            const measureBtn = document.getElementById('measureBtn');
            const clearBtn = document.getElementById('clearBtn');
            const zoomInBtn = document.getElementById('zoomInBtn');
            const zoomOutBtn = document.getElementById('zoomOutBtn');
            const zoomInBtnSmall = document.getElementById('zoomInBtnSmall');
            const zoomOutBtnSmall = document.getElementById('zoomOutBtnSmall');
            const resetViewBtn = document.getElementById('resetViewBtn');
            const workspace = document.getElementById('workspace');
            const imageCanvas = document.getElementById('imageCanvas');
            const overlayCanvas = document.getElementById('overlayCanvas');
            const statusValue = document.getElementById('statusValue');
            const distanceValue = document.getElementById('distanceValue');
            const zoomValue = document.getElementById('zoomValue');
            const zoomDisplay = document.getElementById('zoomDisplay');
            const modeValue = document.getElementById('modeValue');
            const currentMode = document.getElementById('currentMode');
            const modeIndicator = document.getElementById('modeIndicator');
            const lineColorInput = document.getElementById('lineColor');
            
            const ctx = imageCanvas.getContext('2d');
            const overlayCtx = overlayCanvas.getContext('2d');
            
            // 状态变量
            let isMeasuring = false;
            let isDragging = false;
            let originX = 0;
            let originY = 0;
            let scale = 1;
            let image = null;
            let measurements = [];
            let currentMeasurement = null;
            let hoverX = 0;
            let hoverY = 0;
            let lineColor = '#e74c3c'; // 默认红色
            const BASE_LINE_WIDTH = 2; // 基准线条宽度
            
            // 初始化
            resizeCanvases();
            updateStatus('就绪');
            
            // 事件监听
            uploadBtn.addEventListener('click', () => imageUpload.click());
            imageUpload.addEventListener('change', handleImageUpload);
            measureBtn.addEventListener('click', toggleMeasuring);
            clearBtn.addEventListener('click', clearMeasurements);
            zoomInBtn.addEventListener('click', () => zoomImage(0.1));
            zoomOutBtn.addEventListener('click', () => zoomImage(-0.1));
            zoomInBtnSmall.addEventListener('click', () => zoomImage(0.1));
            zoomOutBtnSmall.addEventListener('click', () => zoomImage(-0.1));
            resetViewBtn.addEventListener('click', resetImage);
            lineColorInput.addEventListener('input', (e) => {
                lineColor = e.target.value;
                drawImage();
                drawOverlay();
            });
            
            window.addEventListener('resize', resizeCanvases);
            workspace.addEventListener('mousemove', handleMouseMove);
            workspace.addEventListener('mousedown', handleMouseDown);
            workspace.addEventListener('mouseup', handleMouseUp);
            workspace.addEventListener('mouseleave', handleMouseUp);
            workspace.addEventListener('wheel', handleWheel);
            
            // 调整Canvas大小
            function resizeCanvases() {
                overlayCanvas.width = workspace.clientWidth;
                overlayCanvas.height = workspace.clientHeight;
                drawOverlay();
            }
            
            // 处理图片上传
            function handleImageUpload(e) {
                const file = e.target.files[0];
                if (file && file.type.match('image.*')) {
                    // 上传新图片时清除之前的标注
                    clearMeasurements();
                    
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        loadImage(e.target.result);
                    };
                    reader.readAsDataURL(file);
                }
            }
            
            // 加载图片
            function loadImage(src) {
                image = new Image();
                image.onload = function() {
                    // 确保canvas尺寸与工作区匹配
                    imageCanvas.width = workspace.clientWidth;
                    imageCanvas.height = workspace.clientHeight;
                    
                    // 重置变换和原点
                    scale = 1;
                    
                    // 自动缩放小图片，确保图片在工作区中可见
                    const workspaceWidth = workspace.clientWidth;
                    const workspaceHeight = workspace.clientHeight;
                    const maxDimension = Math.max(image.width, image.height);
                    const minWorkspaceDimension = Math.min(workspaceWidth, workspaceHeight) * 0.7; // 70%的工作区尺寸
                    
                    // 如果图片太小，自动放大
                    if (maxDimension < minWorkspaceDimension) {
                        scale = minWorkspaceDimension / maxDimension;
                    }
                    
                    // 居中显示图片
                    originX = workspaceWidth / 2 - (image.width * scale) / 2;
                    originY = workspaceHeight / 2 - (image.height * scale) / 2;
                    
                    drawImage();
                    drawOverlay();
                    updateZoomInfo();
                    updateStatus('图片已加载，之前的标注已清除');
                };
                image.src = src;
            }
            
            // 绘制图片和测量结果
            function drawImage() {
                if (!image) return;
                
                // 确保canvas尺寸与工作区匹配
                imageCanvas.width = workspace.clientWidth;
                imageCanvas.height = workspace.clientHeight;
                
                ctx.clearRect(0, 0, imageCanvas.width, imageCanvas.height);
                ctx.save();
                
                // 应用平移和缩放变换
                ctx.translate(originX, originY);
                ctx.scale(scale, scale);
                ctx.drawImage(image, 0, 0);
                
                // 绘制所有测量（线条宽度根据缩放反向调整）
                measurements.forEach(measurement => {
                    drawMeasurement(measurement);
                });
                
                ctx.restore();
            }
            
            // 绘制覆盖层
            function drawOverlay() {
                overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
                
                if (!image) return;
                
                // 绘制十字准星（鼠标位置）
                if (isMeasuring) {
                    drawCrosshair();
                }
                
                // 绘制当前测量
                if (currentMeasurement) {
                    drawCurrentMeasurement();
                }
            }
            
            // 绘制十字准星（鼠标位置）
            function drawCrosshair() {
                overlayCtx.save();
                overlayCtx.strokeStyle = lineColor;
                overlayCtx.lineWidth = BASE_LINE_WIDTH;
                overlayCtx.setLineDash([5, 5]);
                
                // 水平线
                overlayCtx.beginPath();
                overlayCtx.moveTo(0, hoverY);
                overlayCtx.lineTo(overlayCanvas.width, hoverY);
                overlayCtx.stroke();
                
                // 垂直线
                overlayCtx.beginPath();
                overlayCtx.moveTo(hoverX, 0);
                overlayCtx.lineTo(hoverX, overlayCanvas.height);
                overlayCtx.stroke();
                
                overlayCtx.restore();
            }
            
            // 绘制工字型标记（用于测量端点）
            function drawIBeam(x, y, context, lineWidth) {
                // 横向线（工字型的横）
                context.beginPath();
                context.moveTo(x - 10, y);
                context.lineTo(x + 10, y);
                context.stroke();
                
                // 纵向线（工字型的竖）
                context.beginPath();
                context.moveTo(x, y - 5);
                context.lineTo(x, y + 5);
                context.stroke();
            }
            
            // 绘制当前测量（临时线条）
            function drawCurrentMeasurement() {
                const { start, end } = currentMeasurement;
                
                overlayCtx.save();
                
                // 线条宽度保持基准宽度，不随缩放变化
                overlayCtx.strokeStyle = lineColor;
                overlayCtx.lineWidth = BASE_LINE_WIDTH;
                
                const startScreenX = start.x * scale + originX;
                const startScreenY = start.y * scale + originY;
                drawIBeam(startScreenX, startScreenY, overlayCtx, BASE_LINE_WIDTH);
                
                // 如果正在拖动，绘制终点和连线
                if (end) {
                    const endScreenX = end.x * scale + originX;
                    const endScreenY = end.y * scale + originY;
                    
                    // 绘制终点工字型
                    drawIBeam(endScreenX, endScreenY, overlayCtx, BASE_LINE_WIDTH);
                    
                    // 绘制连线
                    overlayCtx.beginPath();
                    overlayCtx.moveTo(startScreenX, startScreenY);
                    
                    // 限制为水平或垂直
                    const dx = Math.abs(endScreenX - startScreenX);
                    const dy = Math.abs(endScreenY - startScreenY);
                    
                    if (dx > dy) {
                        // 水平线
                        overlayCtx.lineTo(endScreenX, startScreenY);
                    } else {
                        // 垂直线
                        overlayCtx.lineTo(startScreenX, endScreenY);
                    }
                    
                    overlayCtx.stroke();
                    
                    // 绘制距离文本
                    const distance = calculateDistance(start, end);
                    const midX = (startScreenX + endScreenX) / 2;
                    const midY = (startScreenY + endScreenY) / 2;
                    
                    overlayCtx.fillStyle = lineColor;
                    overlayCtx.font = '14px Arial';
                    overlayCtx.fillText(`${distance} 像素`, midX + 5, midY);
                }
                
                overlayCtx.restore();
            }
            
            // 绘制已完成的测量（最终线条）
            function drawMeasurement(measurement) {
                const { start, end, distance } = measurement;
                
                ctx.save();
                
                // 线条宽度根据缩放比例反向调整
                // 当图片放大时，线条宽度减小，抵消缩放带来的变粗效果
                ctx.strokeStyle = lineColor;
                ctx.lineWidth = BASE_LINE_WIDTH / scale;
                
                // 应用原点偏移，确保测量标记位置正确
                const startScreenX = start.x;
                const startScreenY = start.y;
                const endScreenX = end.x;
                const endScreenY = end.y;
                
                drawIBeam(startScreenX, startScreenY, ctx, BASE_LINE_WIDTH / scale);
                drawIBeam(endScreenX, endScreenY, ctx, BASE_LINE_WIDTH / scale);
                
                // 绘制连线
                ctx.beginPath();
                ctx.moveTo(startScreenX, startScreenY);
                ctx.lineTo(endScreenX, endScreenY);
                ctx.stroke();
                
                // 绘制距离文本
                const midX = (startScreenX + endScreenX) / 2;
                const midY = (startScreenY + endScreenY) / 2;
                
                ctx.fillStyle = lineColor;
                ctx.font = '14px Arial';
                ctx.fillText(`${distance} 像素`, midX + 5, midY);
                
                ctx.restore();
            }
            
            // 计算距离
            function calculateDistance(start, end) {
                const dx = Math.abs(end.x - start.x);
                const dy = Math.abs(end.y - start.y);
                return Math.round(Math.sqrt(dx * dx + dy * dy));
            }
            
            // 切换测量模式
            function toggleMeasuring() {
                isMeasuring = !isMeasuring;
                if (isMeasuring) {
                    measureBtn.textContent = '停止测量';
                    measureBtn.classList.add('btn-danger');
                    measureBtn.classList.remove('btn-success');
                    workspace.style.cursor = 'crosshair';
                    updateStatus('测量模式：点击选择起点');
                    modeIndicator.style.display = 'block';
                } else {
                    measureBtn.textContent = '开始测量';
                    measureBtn.classList.add('btn-success');
                    measureBtn.classList.remove('btn-danger');
                    currentMeasurement = null;
                    workspace.style.cursor = 'grab';
                    updateStatus('就绪');
                    modeIndicator.style.display = 'none';
                }
                drawOverlay();
            }
            
            // 清除所有测量
            function clearMeasurements() {
                measurements = [];
                currentMeasurement = null;
                distanceValue.textContent = '0 像素';
                drawImage();
                drawOverlay();
                updateStatus('已清除所有标注');
            }
            
            // 重置图片
            function resetImage() {
                if (!image) return;
                
                scale = 1;
                originX = workspace.clientWidth / 2 - image.width / 2;
                originY = workspace.clientHeight / 2 - image.height / 2;
                currentMeasurement = null;
                
                drawImage();
                drawOverlay();
                updateZoomInfo();
                updateStatus('视图已重置');
            }
            
            // 缩放图片
            function zoomImage(amount) {
                if (!image) return;
                
                const newScale = scale + amount;
                if (newScale >= 0.1 && newScale <= 5) {
                    scale = newScale;
                    drawImage();
                    drawOverlay();
                    updateZoomInfo();
                }
            }
            
            // 处理鼠标移动
            function handleMouseMove(e) {
                if (!image) return;
                
                const rect = workspace.getBoundingClientRect();
                hoverX = e.clientX - rect.left;
                hoverY = e.clientY - rect.top;
                
                // 处理图片拖动（仅在未测量时可拖拽）
                if (!isMeasuring && isDragging) {
                    originX += e.movementX;
                    originY += e.movementY;
                    drawImage();
                    drawOverlay();
                    return;
                }
                
                // 处理测量中的鼠标移动
                if (isMeasuring && currentMeasurement && currentMeasurement.start) {
                    const imgX = (hoverX - originX) / scale;
                    const imgY = (hoverY - originY) / scale;
                    
                    // 限制为水平或垂直
                    const startScreenX = currentMeasurement.start.x * scale + originX;
                    const startScreenY = currentMeasurement.start.y * scale + originY;
                    
                    const dx = Math.abs(hoverX - startScreenX);
                    const dy = Math.abs(hoverY - startScreenY);
                    
                    if (dx > dy) {
                        // 水平线
                        currentMeasurement.end = { x: imgX, y: currentMeasurement.start.y };
                        currentMode.textContent = '水平测量';
                    } else {
                        // 垂直线
                        currentMeasurement.end = { x: currentMeasurement.start.x, y: imgY };
                        currentMode.textContent = '垂直测量';
                    }
                    
                    drawOverlay();
                } else if (isMeasuring) {
                    drawOverlay();
                }
            }
            
            // 处理鼠标按下
            function handleMouseDown(e) {
                if (!image) return;
                
                // 仅在未测量时允许拖拽
                if (!isMeasuring) {
                    isDragging = true;
                    workspace.style.cursor = 'grabbing';
                }
                
                if (isMeasuring) {
                    const imgX = (hoverX - originX) / scale;
                    const imgY = (hoverY - originY) / scale;
                    
                    if (!currentMeasurement) {
                        // 开始新测量
                        currentMeasurement = {
                            start: { x: imgX, y: imgY },
                            end: null
                        };
                        updateStatus('测量中：选择终点位置');
                    } else {
                        // 完成当前测量
                        const distance = calculateDistance(currentMeasurement.start, currentMeasurement.end);
                        measurements.push({
                            start: { ...currentMeasurement.start },
                            end: { ...currentMeasurement.end },
                            distance: distance
                        });
                        
                        distanceValue.textContent = `${distance} 像素`;
                        updateStatus('测量完成');
                        
                        // 准备下一次测量
                        currentMeasurement = null;
                        drawImage();
                    }
                    
                    drawOverlay();
                }
            }
            
            // 处理鼠标释放
            function handleMouseUp() {
                if (!isMeasuring) {
                    isDragging = false;
                    workspace.style.cursor = 'grab';
                }
            }
            
            // 处理鼠标滚轮
            function handleWheel(e) {
                if (!image) return;
                
                e.preventDefault();
                const delta = e.deltaY > 0 ? -0.1 : 0.1;
                zoomImage(delta);
            }
            
            // 更新缩放信息
            function updateZoomInfo() {
                const zoomPercent = Math.round(scale * 100);
                zoomValue.textContent = `${zoomPercent}%`;
                zoomDisplay.textContent = `${zoomPercent}%`;
            }
            
            // 更新状态
            function updateStatus(status) {
                statusValue.textContent = status;
            }
        });
    </script>
</body>
</html>
    